import { dividerProps } from 'element-plus';
<template>
  <div class="h-full flex-col">
    <SearchForm @handle-reset="resetParams" @handle-search="getList">
      <el-form :model="searchForm" inline>
        <el-form-item label="시간선택">
          <MyCombinePiker :dateTimeRange="_dateTimeRange" @changeHandle="timePickChangeHandle" />
        </el-form-item>

        <el-form-item>
          <el-input v-model="searchForm.agent_player_id" placeholder="로얄회원ID" />
        </el-form-item>

        <el-form-item>
          <el-input v-model="searchForm.game_type" placeholder="게임타입" />
        </el-form-item>

        <el-form-item>
          <el-input v-model="searchForm.table_name" placeholder="테이블명" />
        </el-form-item>

      </el-form>
    </SearchForm>
    <div class="page-card h-full m-table-position" v-loading="loading">
      <div class="m-bet-amount-sum">
        <span>총 베팅금액:</span>
        <el-tag :type="betAmountSum > 0 ? 'danger' : 'success'">
          {{ formatNumber(betAmountSum) }}
        </el-tag>
      </div>

      <MyTable :tableData="tableData" :tableColumn="tableColumn" v-slot="sp">
        <el-table :data="tableData" style="width: 100%" :highlight-current-row="true">
          <!-- <el-table-column v-if="sp.ctc.includes('GUID')" label="GUID" prop="guid" align="center" width="100">
            <template #default="{ row }">
              <div v-for="(item, index) in row.player_id" :key="index">{{ row.guid }}</div>
            </template>
          </el-table-column> -->
          <el-table-column v-if="sp.ctc.includes('GUID')" label="GUID" prop="guid" align="center" width="100" />
          <el-table-column v-if="sp.ctc.includes('EVO회원ID')" label="EVO회원ID" align="center" width="300">
            <template #default="{ row }">
              <div v-for="(item, index) in row.player_id" :key="index">{{ item }}</div>
            </template>
          </el-table-column>
          <el-table-column v-if="sp.ctc.includes('게임타입')" label="게임타입" prop="game_type" align="center" width="200">
            <template #default="{ row }">
              <div v-for="(item, index) in row.player_id" :key="index">{{ row.game_type }}</div>
            </template>
          </el-table-column>
          <el-table-column v-if="sp.ctc.includes('테이블명')" label="테이블명" prop="table_name" align="center" width="250">
            <template #default="{ row }">
              <div v-for="(item, index) in row.player_id" :key="index">{{ row.table_name }}</div>
            </template>
          </el-table-column>
          <el-table-column v-if="sp.ctc.includes('테이블ID')" label="테이블ID" prop="table_id" align="center" width="200">
            <template #default="{ row }">
              <div v-for="(item, index) in row.player_id" :key="index">{{ row.table_id }}</div>
            </template>
          </el-table-column>
          <el-table-column v-if="sp.ctc.includes('플레이어게임ID')" label="플레이어게임ID" align="center" width="400">
            <template #default="{ row }">
              <div v-for="(item, index) in row.player_game_id" :key="index">{{ item }}</div>
            </template>
          </el-table-column>
          <el-table-column v-if="sp.ctc.includes('배팅내역')" label="배팅내역" align="center" width="250">
            <template #default="{ row }">
              <div v-for="(item, index) in row.code" :key="index" @click="gameLogEvoHandle(row, index)">
                <el-tag class="m-cursor-pointer">{{ item }}</el-tag>
              </div>
            </template>
          </el-table-column>
          <el-table-column v-if="sp.ctc.includes('시작시간')" label="시작시간" align="center" width="200">
            <template #default="{ row }">
              <div v-for="(item, index) in row.player_game_id" :key="index">{{ row.started_at }}</div>
            </template>
          </el-table-column>
          <el-table-column v-if="sp.ctc.includes('종료시간')" label="종료시간" align="center" width="200">
            <template #default="{ row }">
              <div v-for="(item, index) in row.player_game_id" :key="index">{{ row.settled_at }}</div>
            </template>
          </el-table-column>
          <el-table-column v-if="sp.ctc.includes('게임 결과')" label="게임 결과" prop="" align="center" width="300">
            <template #default="{ row }">
              <el-tooltip v-for="(item, index) in row.player_game_id" :key="index" class="box-item" effect="dark"
                placement="top-start" :content="row.result" raw-content>
                <div class="m-result-text">
                  {{ row.result }}
                </div>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column v-if="sp.ctc.includes('그룹ID')" label="그룹ID" prop="game_id" align="center" width="250">
            <template #default="{ row }">
              <div v-for="(item, index) in row.player_game_id" :key="index">{{ row.game_id }}</div>
            </template>
          </el-table-column>
          <el-table-column v-if="sp.ctc.includes('게임딜러')" label="게임딜러" align="center" width="250">
            <template #default="{ row }">
              <div v-for="(item, index) in row.player_game_id" :key="index">{{ row.dealerNameDivDealerUid }}</div>
            </template>
          </el-table-column>
          <el-table-column v-if="sp.ctc.includes('베팅금액')" label="베팅금액" align="center" width="120" prop="wager" sortable>
            <template #default="{ row }">
              <div v-for="(item, index) in row.wager" :key="index">{{ formatNumber(item) }}</div>
            </template>
          </el-table-column>
          <el-table-column v-if="sp.ctc.includes('지급금액')" label="지급금액" align="center" width="120" prop="payout" sortable>
            <template #default="{ row }">
              <div v-for="(item, index) in row.payout" :key="index">{{ formatNumber(item) }}</div>
            </template>
          </el-table-column>
          <el-table-column v-if="sp.ctc.includes('회원손익금액')" label="회원손익금액" align="center" width="120">
            <template #default="{ row }">
              <div v-for="(item, index) in row.payoutSubWager" :key="index">
                <el-tag :type="row.payoutSubWager > 0 ? 'danger' : 'success'">
                  {{ formatNumber(item) }}
                </el-tag>
              </div>
            </template>
          </el-table-column>
        </el-table>

        <Pagination :pageable="page" :handleSizeChange="handleSizeChange" :handleCurrentChange="handleCurrentChange" />
      </MyTable>

      <el-drawer v-model="gameLogEvoDrawer" :title="gameLogEvoDrawerTitle" direction="rtl">
        <el-table :data="gameLogEvoDrawerList" style="width: 100%">
          <el-table-column label="상세배팅내역" prop="code" align="center" width="200" />
          <el-table-column label="배팅금액" align="center">
            <template #default="{ row }">
              {{ formatNumber(row.stake) }}
            </template>
          </el-table-column>
          <el-table-column label="지급금액" align="center" width="120" prop="payout">
            <template #default="{ row }">
              {{ formatNumber(Number(row.stake) + Number(row.payout)) }}
            </template>
          </el-table-column>
          <el-table-column label="손익금" align="center">
            <template #default="{ row }">
              {{ formatNumber(row.payout) }}
            </template>
          </el-table-column>
        </el-table>
      </el-drawer>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref } from 'vue';
import { useTable } from '@/hooks/useTable';
import { gameLogEvoApi } from '@/api/record/index';
import {
  formatNumber,
  dataTimeRangeCurTwo,
  formatDate,
  timestampToSeoul,
  dateTransToSeoulTime
} from '@/utils/util';
import MyTable from '@/components/MyTable';
import { useMyDateRange } from '@/hooks/useMyDateRange';
import MyCombinePiker from '@/components/MyCombinePiker';

const tableColumn = ref([
  'GUID',
  'EVO회원ID',
  '게임타입',
  '테이블명',
  '테이블ID',
  '플레이어게임ID',
  '배팅내역',
  '시작시간',
  '종료시간',
  '게임 결과',
  '그룹ID',
  '게임딜러',
  '베팅금액',
  '지급금액',
  '회원손익금액'
]);

const gameLogEvoDrawer = ref(false);
const gameLogEvoDrawerTitle = ref('');
const gameLogEvoDrawerList = ref([]);
const gameLogEvoHandle = (row: any, index: number) => {
  gameLogEvoDrawer.value = true;
  gameLogEvoDrawerTitle.value = `회원계정: ${row.participants[index]['player_id']}`;
  gameLogEvoDrawerList.value = row.participants[index]['bets'];
};

const gameResultStrGet = (dataItem: any) => {
  var gameResult = JSON.parse(dataItem);
  if (gameResult.banker && gameResult.player && gameResult.outcome) {
    var displayText =
      '뱅커 카드: ' +
      gameResult.banker.cards.join(', ') +
      '，점수: ' +
      gameResult.banker.score +
      '<br /> 플레이어 카드: ' +
      gameResult.player.cards.join(', ') +
      '，점수: ' +
      gameResult.player.score +
      '<br /> 결과: ' +
      (gameResult.outcome === 'Tie' ? '무승부' : gameResult.outcome);
    return displayText;
  }

  if (gameResult.outcome && gameResult.outcome.type) {
    return '결과 유형: ' + gameResult.outcome.type;
  }
};

const _dateTimeRange = dataTimeRangeCurTwo(-1);

const searchForm = reactive({
  agent_player_id: '',
  agent_player_name: '',
  player_id: '',
  game_type: '',
  table_name: '',
  start_ts: dateTransToSeoulTime(_dateTimeRange[0]),
  end_ts: dateTransToSeoulTime(_dateTimeRange[1])
});

const timePickChangeHandle = (timestamp: number, type: string) => {
  searchForm[type] = timestamp;
};

const dataCallBack = (data: any) => {
  const _data = data.data;
  let _list = _data.games.map((item: any) => {
    item._rawWager = item.wager;
    let playerIdArr: any = [];
    let playGameIdArr: any = [];
    let codeArr: any = [];
    let payoutArr: any = [];
    let wagerArr: any = [];
    let payoutSubWagerArr: any = [];
    item.participants.map((item: any) => {
      playerIdArr.push(item.player_id)
      playGameIdArr.push(item.player_game_id)
      codeArr.push(item['bets'][0]['code'])
      let _payout = item['bets'].reduce((prev: any, cur: any) => {
        return prev + Number(cur.payout)
      }, 0)
      let _wager = item['bets'].reduce((prev: any, cur: any) => {
        return prev + Number(cur.stake)
      }, 0)
      payoutArr.push(_payout)
      wagerArr.push(_wager)
      payoutSubWagerArr.push(_payout - _wager);
    })
    item.player_id = playerIdArr;
    item.player_game_id = playGameIdArr;
    item.code = codeArr;
    item.payout = payoutArr;
    item.wager = wagerArr;
    item.payoutSubWager = payoutSubWagerArr;

    item.started_at = timestampToSeoul(item.started_at, 'Y-m-d H:i:s', 1);
    item.settled_at = timestampToSeoul(item.settled_at, 'Y-m-d H:i:s', 1);

    item.dealerNameDivDealerUid = `${item.dealer_name}/${item.dealer_uid}`;

    item.result = gameResultStrGet(item.result);

    return item;
  });

  return {
    list: _list,
    total: _data.total_count
  };
};

const { tableData, page, loading, resetParams, getList, handleCurrentChange, handleSizeChange } =
  useTable({
    apiFn: gameLogEvoApi,
    params: searchForm,
    callback: dataCallBack
  });

const betAmountSum = ref(0);

watch(tableData, (data: any) => {
  const amount = tableData.value.reduce((prev: number, item: any) => {
    return prev + Number(item._rawWager);
  }, 0);
  betAmountSum.value = amount;
});
</script>

<style lang="scss" scoped>
.m-table-position {
  position: relative;
}

.m-bet-amount-sum {
  position: absolute;
  bottom: 0;
  left: 1.25rem;
  height: 56px;
  width: 300px;
  display: flex;
  align-items: center;
  justify-content: flex-start;
  font-size: 14px;
}

.m-bet-amount-sum span {
  margin-right: 10px;
}

.m-result-text {
  width: 300px;
  height: 23px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
</style>
